﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CMN.Models;
using CMN.Entity;
using CMN.Common;
using CMN.Config;
using CMN.Models.Interfaces;
using System.Text.RegularExpressions;
using System.IO;
namespace CMN.Domain
{
    public partial class frmAddSite : Form
    {
        private AsyncPLInsert asyncPLInsert=null;
        public int Id = 0;
        public frmAddSite()
        {
            InitializeComponent();
        }
        public frmAddSite(int id)
        {
            InitializeComponent();
            Id = id;
           
            
           
            
        }
        private void frmAddSite_Load(object sender, EventArgs e)
        {
            if (Id != 0)
            {
                IDataService<DomainsEntity> DomainsSv = ServiceBuilder.BuildDomainsService();
                DomainsEntity site = DomainsSv.Look(Id);
                if (site != null)
                {
                    tbBR.Text = site.BR.ToString();
                    tbIndex.Text = site.IndexNum.ToString();
                    //tbUserName.Text = site.LoginName;
                    tbMark.Text = site.Mark;
                    tbPR.Text = site.PR.ToString();
                    //cmboxType.Text = site.SendUrlType;
                    tbOutUrlNum.Text = site.OutUrlNum;
                    tbSiteName.Text = site.SiteName;
                    tbUrl.Text = site.SiteUrl;
                    tbDeleteTime.Text = site.DeleteTime.ToString();
                    cmboxSiteType.Text = site.SiteType;
                }
            }
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbUrl.Text))
            {
                MessageBox.Show("请填写网站URL");
                return;
            }
            DomainsEntity site = new DomainsEntity();
            site.SiteUrl = tbUrl.Text;
            IDataService<DomainsEntity> DomainsSv = ServiceBuilder.BuildDomainsService();
            if (Id == 0)
            {
                int recordNum = 0;
                QueryParam qp = new QueryParam();
                qp.Where = " siteUrl='" + site.SiteUrl + "'";
                List<DomainsEntity> siteList = DomainsSv.List(qp, out recordNum);
                if (siteList.Count > 0)
                {
                    MessageBox.Show("该网址已添加！");
                    return;
                }
            }

           // site.DeleteTime=
            site.BR = Utils.StringToInt(tbBR.Text, 0);
            site.IndexNum = tbIndex.Text;
           // site.LoginName = tbUserName.Text;
            site.Mark = tbMark.Text;
            site.PR = Utils.StringToInt(tbPR.Text, 0);
            //site.SendUrlType = cmboxType.Text;
            site.SiteType = cmboxSiteType.Text;
            site.SiteName = tbSiteName.Text;
            site.OutUrlNum = tbOutUrlNum.Text;
            site.DeleteTime = Utils.StringToDataTime(tbDeleteTime.Text);
            if (Id == 0)
                DomainsSv.Insert(site);
            else
            {
                site.ID  = Id;
                DomainsSv.Update(site);

            }
            clear();
            //List<DomainsEntity> sys_moduleList = DomainsSv.List(qp, out recordNum);
        }
        private void clear()
        {
            tbBR.Text = "";
            tbIndex.Text = "";
            tbMark.Text = "";
            tbPR.Text = "";
            tbSiteName.Text = "";
            tbUrl.Text = "";
            
        }

        private void btnGetInfo_Click(object sender, EventArgs e)
        {
            DomainsEntity site = new DomainsEntity();
            site = GetDomains(tbUrl.Text);
            try
            {
                Uri baseUri = new Uri(tbUrl.Text);
                tbUrl.Text = site.SiteUrl;
                tbOutUrlNum.Text = site.OutUrlNum;
                tbIndex.Text = site.IndexNum.ToString();
                tbOutUrlNum.Text = site.OutUrlNum;
                
                tbPR.Text = site.PR.ToString();
                tbBR.Text = site.BR.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        public DomainsEntity GetDomains(string url)
        {
            DomainsEntity site = new DomainsEntity();
           
            try
            {
                //索引
                Uri baseUri = new Uri(url);
                site.SiteUrl = "http://" + baseUri.Authority.ToLower();
                string strContent = Utils.GetRequestString("http://www.baidu.com/s?ie=UTF-8&wd=site%3A" + baseUri.Authority, 16000, 1, Encoding.GetEncoding("utf-8"), "http://www.baidu.com/index.php?tn=icafemedia_18_pg");
               string index = Utils.GetCutString(strContent, "该网站共有", "个网页被百度收录", false);
                if(index=="")
                    index = Utils.GetCutString(strContent, "找到相关结果数约", "个", false);
                if (index == "" && strContent.IndexOf("很抱歉") > -1)
                {
                    index = "0";
                }
                site.IndexNum = index.Replace(",", "");
               //外链

               strContent = Utils.GetRequestString("http://www.baidu.com/s?ie=UTF-8&wd=\"www." + baseUri.Authority + "\"", 16000, 1, Encoding.GetEncoding("utf-8"), null);
                index = Utils.GetCutString(strContent, "百度为您找到相关结果约", "个", false);
               if (index == "")
                   index = Utils.GetCutString(strContent, "找到相关结果数约", "个", false);
               if (index == "" && strContent.IndexOf("很抱歉")>-1)
               {
                   index = "0";
               }
               site.OutUrlNum = index.Replace(",", "");
                //pr
               strContent = Utils.GetRequestString("http://seo.chinaz.com/?host=" + baseUri.Authority, 16000, 1, Encoding.GetEncoding("utf-8"), null);
               string strPR = Utils.GetCutString(strContent, "/template/default/images/ranks/Rank_", ".gif", false);
               if (strPR.Trim() == "-2")
                   strPR = "0";
               site.PR = Utils.StringToInt(strPR, 0);
               string strBR = Utils.GetCutString(strContent, "/template/default/images/baiduapp/", ".gif", false);
               site.BR = Utils.StringToInt(strBR, 0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return site;
           
        }

        private void btnFile_Click(object sender, EventArgs e)
        {
             OpenFileDialog openFileDialog = new OpenFileDialog();
         
            
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {

                tbPl.Text = openFileDialog.FileName;
            }
            
          
        }
       
        
        void AsyncImport_TaskDone(object sender, EventArgs e)
        {
            btnPL.Enabled = true;
            lbUpdate.Text = "完成";
        }
        void AsyncImport_TaskProgress(object sender, EventArgs e)
        {
            AsyncEventArgs pAsyncEventArgs = e as AsyncEventArgs;
            int step = (int)pAsyncEventArgs.getObjects[0];
            lbUpdate.Text = "共" + pAsyncEventArgs.action.ToString() + "当前第" + (step + 1).ToString();

        }
        private void btnPL_Click(object sender, EventArgs e)
        {
            if (!File.Exists(tbPl.Text)) return;
            this.asyncPLInsert = new AsyncPLInsert(this);
            this.asyncPLInsert.TaskProgress += new EventHandler(AsyncImport_TaskProgress);
            this.asyncPLInsert.TaskDone += new EventHandler(AsyncImport_TaskDone);
            asyncPLInsert.StrWhere = tbPl.Text;
            asyncPLInsert.Start();
            btnPL.Enabled = false;
           
           
        }

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            //停止工作线程
            if (this.asyncPLInsert != null)
                this.asyncPLInsert.Stop();
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }


       
    }
}
